home *** CD-ROM | disk | FTP | other *** search
/ Almathera Ten Pack 3: CDPD 3 / Almathera Ten on Ten - Disc 3: CDPD3.iso / scope / 051-075 / scopedisk54 / fold / fold.c < prev    next >
C/C++ Source or Header  |  1995-03-18  |  2KB  |  83 lines

  1. #include <stdio.h>
  2. #include <fcntl.h>
  3.  
  4. FILE    *infile;
  5.  
  6. char    buf[8*BUFSIZ];
  7. int     lin_len=80;
  8.  
  9. void
  10. main( argc, argv )
  11. int argc;
  12. char *argv[];
  13. {
  14.         int n;
  15.         int start=1;
  16.  
  17.         if( *argv[1] == '-' )
  18.         {
  19.                 lin_len = atoi( argv[1] ) * -1;
  20.                 start ++;
  21.         }
  22.  
  23.         if( lin_len <= 0 ) lin_len = 80;
  24.  
  25.         if( argc <= start )
  26.         {
  27.                 fprintf( stderr, "Breaks lines at space or tab, creating new line\nUsage: %s [>outfile] [-lin_length] file [file ...]\n", argv[0] );
  28.                 exit( 0 );
  29.         }
  30.  
  31.         for( ;start < argc; start ++ )
  32.         {
  33.                 char *p;
  34.                 p = argv[start];
  35.  
  36.                 if( (infile = fopen( p, "r" )) == NULL )
  37.                 {
  38.                         perror( p );
  39.                         continue;
  40.                 }
  41.  
  42.                 while( fgets( buf, BUFSIZ, infile ) != NULL )
  43.                 {
  44.                         buf[strlen(buf)-1] = 0;
  45.                         process( buf );
  46.                         puts(buf);
  47.                         fflush( stdout );
  48.                 }
  49.  
  50.                 fclose( infile );
  51.         }
  52. }
  53.  
  54. process( p )
  55. char p[];
  56. {
  57.         int tablen = 8;
  58.         int i;
  59.         int l = 0;
  60.         int s = 0;
  61.  
  62.         for ( i = 0; i < BUFSIZ && p[i]; i++ )
  63.         {
  64.                 if ( p[i] == '\t' )
  65.                         l = ((l + tablen)/tablen)*tablen;
  66.                 else
  67.                         l ++;
  68.  
  69.                 if ( l > lin_len )
  70.                 {
  71.                         for (l = i; l > s; l--)
  72.                                 if (p[l] == ' ' || p[l] == '\t')
  73.                                 {
  74.                                         p[l] = '\n';
  75.                                         i = l+1;
  76.                                         s = i;
  77.                                         l = 0;
  78.                                         break;
  79.                                 }
  80.                 }
  81.         }
  82. }
  83.